﻿using System;
using System.Linq;
using System.Data.Linq;
using System.Data.SqlClient;

using Fuse8.DomainFramework.Domain;

namespace Fuse8.DomainFramework.DataAccess.LinqDatabase
{
    /// <summary>
    /// 
    /// </summary>
    public class LinqUnitOfWork<T> : IDbUnitOfWork, IUnitOfWork<T>, IDisposable where T : class, IEntityObject
    {
        #region Fields

        private bool _isDisposed = false;

        #endregion

        #region Properties

        /// <summary>
        /// 
        /// </summary>
        public SqlConnection Connection 
        {
            get
            {
                return CurrentContext.Connection as SqlConnection;
            }
            set
            {
                throw new NotSupportedException("Setting connection doesn't support directly. Connection are created when DataContext constructing");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public SqlTransaction Transaction
        {
            get
            {
                return CurrentContext.Transaction as SqlTransaction;
            }
            set
            {
                throw new NotSupportedException();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public virtual DataContext CurrentContext
        {
            get;
            set;
        } 

        #endregion

        #region Constructor

        /// <summary>
        /// 
        /// </summary>
        public LinqUnitOfWork()
        { } 

        #endregion

        #region IDisposable Members

        /// <summary>
        /// 
        /// </summary>
        ~LinqUnitOfWork()
        {
            Dispose(false);
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                {
                    if (CurrentContext != null)
                    {
                        CurrentContext.Connection.Close();
                        CurrentContext.Dispose();
                        CurrentContext = null;
                    }
                }
            }

            _isDisposed = true;
        }
        
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
